package com.kyw.android_dev_util.util;

import com.kyw.android_dev_util.common.ConstField;
import com.kyw.android_dev_util.common.MessageConstant;
import com.kyw.android_dev_util.exception.BizException;
import org.apache.commons.io.FileUtils;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileUtil {
    public void getFile(){

        try {
            File file = ResourceUtils.getFile("classpath:templates/layout/LinearLayout.xml");
            String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);

            FileUtils.write(new File(ConstField.LAYOUT_PATH +"test.xml"), content,"UTF-8");
            System.out.println(content);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void createLinearLayout(String layoutName){
        //文件是否存在
        File file = new File(ConstField.LAYOUT_PATH + layoutName+".xml");
        if(file.exists()){
            //直接抛出异常
            throw new BizException(MessageConstant.ACCESS_FAILED,"布局文件名已存在");
        }
        //不存在才创建
        try {
            File template = ResourceUtils.getFile("classpath:templates/layout/LinearLayout.xml");
            String content = FileUtils.readFileToString(template, StandardCharsets.UTF_8);
            FileUtils.write(file, content,"UTF-8");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void writeToFile(String path, String content) throws IOException {
        FileUtils.write(new File(path), content,"UTF-8");
    }
    public static boolean checkViewId(String str,Map<String,String> idMap){
        boolean ret = false;
        Set<Map.Entry<String, String>> entrys = idMap.entrySet();  //此行可省略，直接将map.entrySet()写在for-each循环的条件中
        for(Map.Entry<String, String> entry:entrys){
            String key = entry.getKey();
            String value = entry.getValue();
            if(str.contains("view_"+key)){
                ret = true;
                break;
            }
        }
        return ret;
    }
    public static String createIdInCode(String path,Map<String,String> idMap){
        File file = new File(path);
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));//构造一个BufferedReader类来读取文件
            String lineStr = null;
            while((lineStr = br.readLine())!=null){//使用readLine方法，一次读一行
                String readLine = lineStr;
                //先将之前的findViewById清除
                //1.将正在表达式封装成对象Patten 类来实现
                Pattern patternObj = Pattern.compile(".*public.*view_.*;");
                //2.将字符串和正则表达式相关联
                Matcher matcher = patternObj.matcher(readLine);
                //3.String 对象中的matches 方法就是通过这个Matcher和pattern来实现的。
                String pattern2 = ".*=.*findViewById.*R\\.id.*;";
                Pattern patternObj2 = Pattern.compile(pattern2);
                Matcher matcher2 = patternObj2.matcher(readLine);
                if(!matcher.matches() && !matcher2.matches()){
                    result.append(readLine+System.lineSeparator());
                }

            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        String ret = result.toString();

        String findStr = "public void findViews() {";
        int pos = ret.lastIndexOf(findStr);//pos不需要加1
        if(pos == -1){
            String add = "  public void findViews() {" +
                    "   }";
            ret = addContentToEnd(ret, "}", add);
            result = new StringBuilder(ret);
        }
        pos = result.lastIndexOf(findStr);//pos不需要加1

        String addData = "";
        String fieldData="";
        Set<Map.Entry<String, String>> entrys = idMap.entrySet();  //此行可省略，直接将map.entrySet()写在for-each循环的条件中
        for(Map.Entry<String, String> entry:entrys){
            String key = entry.getKey();
            String value = entry.getValue();
            String insertStr = System.lineSeparator() + "       view_"+key+" = findViewById(R.id."+key+");";
            addData +=insertStr;

            String tempField = System.lineSeparator()+"    public "+value+" view_"+key+";";
            fieldData += tempField;
        }
        addData +=System.lineSeparator();
        result.insert(pos + findStr.length() + 1,addData);
        ret = result.toString();

        pos = ret.indexOf("{") + 1;
        result.insert(pos ,fieldData);

        return result.toString();
    }
    public static String addFileContent(String path,String search,String addContent,boolean isBefore){
        File file = new File(path);
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));//构造一个BufferedReader类来读取文件

            String lineStr = null;
            int pos = 0;
            while((lineStr = br.readLine())!=null){//使用readLine方法，一次读一行
                String readLine = lineStr+System.lineSeparator() ;
                result.append(readLine);
                if(search != null && addContent != null){
                    if(lineStr.contains(search)){
                        int temPos = lineStr.indexOf(search);//不加1，往前插入，加1则向后插入
                        if(!isBefore){
                            temPos += 1;
                        }
                        result.insert(pos + temPos,addContent);
                    }
                }
                pos += readLine.length();
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        String ret = result.toString();
        int pos = ret.lastIndexOf("}");//pos不需要加1
        result.insert(pos,"     我是卖报的小行家"+System.lineSeparator());
        ret = result.toString();
        return ret;
    }
    public static String addContentToEnd(String fileContent,String search,String addContent){
        String ret = null;
        int pos = fileContent.lastIndexOf(search);//pos不需要加1
        if(pos != -1){
            StringBuilder stringBuilder = new StringBuilder(fileContent);
            stringBuilder.insert(pos,addContent+System.lineSeparator());
            ret = stringBuilder.toString();
        }
        return ret;
    }
    public static String deleteContent(String path,String pattern){
        String ret = null;
        File file = new File(path);
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));//构造一个BufferedReader类来读取文件

            String lineStr = null;
            int pos = 0;
            while((lineStr = br.readLine())!=null){//使用readLine方法，一次读一行
                String readLine = lineStr;

                //1.将正在表达式封装成对象Patten 类来实现
                Pattern patternObj = Pattern.compile(pattern);
                //2.将字符串和正则表达式相关联
                Matcher matcher = patternObj.matcher(readLine);
                //3.String 对象中的matches 方法就是通过这个Matcher和pattern来实现的。

                if(!matcher.matches()){

                    readLine +=System.lineSeparator() ;
                }

                result.append(readLine);

                pos += readLine.length();
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        ret = result.toString();
        return ret;
    }
    public static Map<String,String> findIds(String path){
        Map<String,String> ret = new HashMap<>();
        File file = new File(path);
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));//构造一个BufferedReader类来读取文件
            String lineStr = null;
            int step = 0;
            String viewType = "";
            while((lineStr = br.readLine())!=null){//使用readLine方法，一次读一行
                String readLine = lineStr;
                //先找开始标签
                String str = readLine.trim();
                if(str.startsWith("<")){
                    step = 1;
                    String[] info = str.split(" ");
                    int temPos = info[0].lastIndexOf(".");
                    if(temPos == -1){
                        viewType = info[0].substring(1,info[0].length());
                    }else {
                        viewType = info[0].substring(temPos+1,info[0].length());
                    }
                }
                if(str.endsWith(">")){//结束标签
                    step = 0;
                }
                if(step == 1){//找到了开始标签
                    String pattern = ".*android:id.*";
                    //1.将正在表达式封装成对象Patten 类来实现
                    Pattern patternObj = Pattern.compile(pattern);
                    //2.将字符串和正则表达式相关联
                    Matcher matcher = patternObj.matcher(str);
                    //3.String 对象中的matches 方法就是通过这个Matcher和pattern来实现的。
                    if(matcher.matches()){
                        int tmpPos = str.indexOf("@+id/");
                        String id = str.substring(tmpPos + "@+id/".length(), str.lastIndexOf("\""));
                        ret.put(id,viewType);
                    }
                }
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    public static void main(String args[]) throws IOException {
       /* String content = deleteContent("f://data.txt",".*findViewById.*");
        LogUtil.debug("内容："+content);*/
        Map<String, String> ids = findIds("E:\\2020Teach\\AndroidQuickLib\\android-assit-lib\\app\\src\\main\\res\\layout\\activity_main.xml");
        String target = "E:\\2020Teach\\AndroidQuickLib\\android-assit-lib\\app\\src\\main\\java\\com\\kyw\\androidquicktest\\MainActivity.java";
        String content = createIdInCode(target, ids);
        writeToFile(target,content);
        /* Set<Map.Entry<String, String>> entrys = ids.entrySet();  //此行可省略，直接将map.entrySet()写在for-each循环的条件中*/

       /* for(Map.Entry<String, String> entry:entrys){
            System.out.println("key值："+entry.getKey()+" value值："+entry.getValue());
        }*/
    }
}
